package com.citywithincity.db;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.citywithincity.db.interfaces.IValueConvert;
import com.citywithincity.db.interfaces.SqlDriver;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

/**
 * 沟通实体类和数据库表的桥梁
 * @author renxueliang
 *
 */
public class Entity<T> {

	private static final Log logger = LogFactory.getLog("sql");
	
	/**
	 * 表名称
	 */
	String tableName;
	
	/**
	 * 字段
	 */
	EntityField[] fields;
	
	private EntityField[] uniqueFields;

	Field autoGenerageField;
	
	String autoGenerageColumn;
	
	private EntityField[] pks;
	
	IValueConvert autoGenerateConvert;

	Schema<T> schema;
	
	int db;
	
	private SqlDriver sqlDriver;

	public String pk;

	public String select;
	
	Entity(Class<T> clazz,int db,String tableName,EntityField[] pks,String pk){
		schema = RuntimeSchema.getSchema(clazz);
		sqlDriver = Db.getDriver(db);
		this.db=  db;
		this.tableName = tableName;
		this.pks = pks;
		this.pk = pk;
	}

	public String getAutoColumnName() {
		return autoGenerageColumn;
	}
	public String getUniqueValue(Object data) {
		if(pks==null || pks.length == 0){
			throw new RuntimeException("请为表"+ getTableName() +"设置主键");
		}
		StringBuilder sb = new StringBuilder(tableName);
		for (EntityField entityField : pks) {
			sb.append('-').append(entityField.get(data));
		}
		return sb.toString();
	}
	
	public int insert(Connection connection,T data) throws SQLException{
		final SqlDriver sqlDriver = this.sqlDriver;
		return sqlDriver.insert(connection,data,this);
	}
	
	
	public void setAutoGenerate(Object entity,Object value) {
		try {
			if(autoGenerateConvert!=null){
				value = autoGenerateConvert.convert(value);
			}
			autoGenerageField.set(entity, value);
		} catch (IllegalArgumentException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
	
	public void setUniqueFields(List<EntityField> uniqueFields) {
		if(uniqueFields.size()>0){
			EntityField[] fields = new EntityField[uniqueFields.size()];
			uniqueFields.toArray(fields);
			this.uniqueFields = fields;
		}
		
	}
	
	
	public T fromDb(ResultSet rs) throws SQLException{
		final Schema<T> schema = this.schema;
		final EntityField[] fields = this.fields;
		
		T entity = schema.newMessage();
		int columnIndex = 1;
		for (EntityField entityField : fields) {
			Object value = rs.getObject(columnIndex++);
			if(value==null){
				continue;
			}
			entityField.set(entity,value);
		}
		return entity;
	}
	
	public List<T> getList(ResultSet rs) throws SQLException{
		List<T> list = new ArrayList<T>();
		while (rs.next()) {
			list.add(fromDb(rs));
		}
		return list;
	}

	/**
	 * 唯一条件
	 * @param entity
	 */
	@SuppressWarnings("rawtypes")
	public void where(Object entity,SqlBuilder builder){
		if(autoGenerageField!=null){
			try {
				builder.where(autoGenerageColumn,autoGenerageField.get(entity));
			} catch (IllegalArgumentException e) {
				throw new RuntimeException(e);
			} catch (IllegalAccessException e) {
				throw new RuntimeException(e);
			}
		}else if(pks!=null){
			for (EntityField entityField : pks) {
				builder.where(entityField.columnName,entityField.get(entity));
			}
		}else{
			throw new RuntimeException("无法update或者delete，因为找不到where条件");
		}
	}

	public EntityField[] getFields() {
		return fields;
	}

	public EntityField[] getPks(){
		return pks;
	}

	public void setFields(EntityField[] fields) {
		this.fields = fields;
	}



	public EntityField[] getUniqueFields() {
		return uniqueFields;
	}



	public String getTableName() {
		return tableName;
	}



	public void setTableName(String tableName) {
		this.tableName = tableName;
	}

	public boolean isAuto() {
		
		return autoGenerageField!=null;
	}

	
	//clone
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Object[] getValues(Object data) {
		final EntityField[] fields = this.fields;
		Object[] result = new Object[ fields.length ];
		int index = 0;
		for (EntityField field : fields) {
			Object value = field.get(data);
			if(value instanceof Map){
				Map newValue = new HashMap();
				newValue.putAll((Map)value);
				value = newValue;
			}
			result[index++] = value;
		}
		return result;
	}


	

	



	
	
	
}
